package com.sunlake.spring.main.model.auth.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunlake.spring.main.common.response.R;
import com.sunlake.spring.main.model.auth.dto.*;
import com.sunlake.spring.main.model.auth.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.stream.Collectors;

/**
 * @author 罗志
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;
    @PostMapping("/login")
    public R login(@RequestBody LoginDTO loginDTO) {
        if (loginDTO.getEmail() == null || loginDTO.getPassword() == null) {
            return R.error(400, "邮箱或密码不能为空");
        } else {
            return authService.login(loginDTO);
        }
    }

    @PostMapping("/verification-code")
    public R verificationCode(@RequestBody VerificationDTO verificationDTO) {
        System.out.println(verificationDTO);
        return authService.VerificationCode(verificationDTO);
    }

    @PostMapping("/verification-code/validate")
    public R validateVerificationCode(@RequestBody VerifyDTO verifyDTO) {
        System.out.println(verifyDTO);
        return authService.validateVerificationCode(verifyDTO);
    }

    @PostMapping("/register")
    public R register(@RequestBody RegisterDTO registerDTO) {
        System.out.println(registerDTO);
        return authService.register(registerDTO);
    }

    @GetMapping("/info")
    public R fetchUserInfo(@RequestHeader(value = "Authorization", required = false) String authorization,
                           @RequestParam(value = "token", required = false) String token
        ) {
        String tokenStr = null;
        if (authorization != null && authorization.toLowerCase().startsWith("bearer ")) {
            tokenStr = authorization.substring(7).trim();
        }
        if (tokenStr == null || tokenStr.isEmpty()) {
            tokenStr = token;
        }
        if (tokenStr == null || tokenStr.isEmpty()) {
            return R.error(400, "缺少访问令牌");
        }
        FetchDTO fetchDTO = new FetchDTO();
        fetchDTO.setToken(tokenStr);
        return authService.fetchUserInfo(fetchDTO);
    }
    @PostMapping("/update")
    public R updateUserInfo(@RequestBody UpdateDTO updateDTO) {
        System.out.println(updateDTO);
        return authService.updateUserInfo(updateDTO);
    }

    @PostMapping("/reset-password")
    public R resetPassword(@RequestBody ResetPasswordDTO resetPasswordDTO) {
        System.out.println(resetPasswordDTO);
        return authService.resetPassword(resetPasswordDTO);
    }
}
